﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MC.RideEventMVC.Models.Entity;

namespace MC.RideEventMVC.Models
{
    public class EventRepository : IEventRepository
    {
        #region Constantes
        private const int THE_LAST = 8;
        #endregion

        #region Fields
        private RideEventDBEntities _context;
        #endregion

        #region Constructors
        public EventRepository()
        {
            _context = new RideEventDBEntities();
        }
        #endregion

        #region Methods
        /// <summary>
        /// Return a list of event taking
        /// only event activated and which the
        /// date begin higher date of today.
        /// </summary>
        /// <returns></returns>
        public List<Event> GetEvents()
        {
            var dateNow = DateTime.Now;
            var list = from evt in _context.Event
                       where evt.Activated
                       where evt.DateBegin.Date > dateNow.Date
                       orderby evt.DateBegin.Date descending
                       select evt;

            var result = list.ToList();

            return result;
        }

        /// <summary>
        /// Return a list of event taking
        /// the five last.
        /// </summary>
        /// <returns></returns>
        public List<Event> GetLastEvents()
        {
            var dateNow = DateTime.Now;
            var list = from evt in _context.Event
                       where evt.Activated
                       where evt.DateBegin.Date > dateNow.Date
                       orderby evt.DateBegin.Date descending
                       select evt;

            var result = list.Take(THE_LAST).ToList();

            return result;
        }

        /// <summary>
        /// Perform un research on events and
        /// return a result as list of event.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public List<Event> ResearchEvents(string text, DateTime date)
        {
            var list = from evt in _context.Event
                       where (evt.Title == text
                       || evt.NamePlace == text)
                       //where (date != null 
                       //&& evt.DateBegin.Date == date.Date)
                       orderby evt.DateBegin.Date descending
                       select evt;

            if (date != null)
            {
                list = list.Where(evt => evt.DateBegin.Date == date.Date);
            }

            List<Event> result = list.ToList();

            return result;
        }

        public bool SuggestEvent()
        {
            bool result = false;

            return result;
        }
        #endregion
    }
}